package cn.congine.wizarpos.mall.action;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import cn.congine.wizarpos.mall.model.MrtTicketDef;
import cn.congine.wizarpos.mall.model.MrtTicketInfo;
import cn.congine.wizarpos.mall.model.SysMerchantDef;
import cn.congine.wizarpos.mall.service.MrtMerchantCardService;
import cn.congine.wizarpos.mall.service.MrtTicketDefService;
import cn.congine.wizarpos.mall.service.MrtTicketInfoService;
import cn.congine.wizarpos.mall.service.SysMerchantDefService;
import cn.congine.wizarpos.mall.service.SysWxChildMerchantTokenService;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WxAuthentication;
import cn.congine.wizarpos.mall.service.impl.WxThirdAuthentication;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.MatrixToImageWriter;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/zhanhui")
public class ZhanHuiAction {
	private final static int SUCCESS = 0;
	private final static int NOCARD = 5;
	
	private final Log log = LogFactory.getLog(getClass());

	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	@Autowired
	private SysMerchantDefService merchantDefService;

	@Autowired
	private MrtTicketDefService ticketDefService;
	
	@Autowired
	private MrtMerchantCardService merchantCardService;

	@Autowired
	private MrtTicketInfoService mrtTicketInfoService;
	
	@Autowired
	private WPosHttpClient wposHttpClient;

	@Autowired
	private WxThirdAuthentication wxAuthentication;
	
	@Autowired
	private SysWxChildMerchantTokenService sysWxChildMerchantTokenService;
	/**
	 * 领取会员券
	 * 
	 * @param mid
	 * @param ticketId
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/index528")
	public ModelAndView index528(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "ticketDefId", required = true) String ticketDefId,
			Model model) {
		
		MrtTicketDef ticketDef = ticketDefService.get(ticketDefId);
		int used = ticketDef.getHbUseNum() == null ? 0 : ticketDef.getHbUseNum();
		if (used < 100) { // 活动券仍有剩余
			model.addAttribute("active", true);
		}
		
		// 判断当前的微信open_id是否已经开通微信会员卡
		JSONObject json = wposHttpClient.getMerchantCardByOpenId(openId, mid);
		String cardId = null;
		if (json.containsKey("code")) {
			int code = json.getIntValue("code");
			if (code == SUCCESS) {
				// 获取对应的会员卡卡号
				JSONObject cardVip = json.getJSONObject("result");
				cardId = cardVip.getString("id");
				// 已经领券的
				MrtTicketInfo ticketInfo = mrtTicketInfoService.getByTicketDefIdAndCardIdAndMid(ticketDefId, cardId, mid);
				if (ticketInfo != null) {
					model.addAttribute("active", true);
				}
			}
		}

		model.addAttribute("mid", mid);
		model.addAttribute("openId", openId);
		model.addAttribute("ticketDefId", ticketDefId);
		
		return new ModelAndView("zhanhui/index528");
	}
	
	
//	/**
//	 * 领取会员券
//	 * 
//	 * @param mid
//	 * @param ticketId
//	 * @param openId
//	 * @return
//	 */
//	@RequestMapping(value = "/gift")
//	public @ResponseBody JSONObject gift(
//			@RequestParam(value = "mid", required = true) String mid,
//			@RequestParam(value = "openId", required = true) String openId,
//			@RequestParam(value = "ticketDefId", required = true) String ticketDefId) {
//		log.info("zhanHuiAction 领取会员券");
//		// 判断当前的微信open_id是否已经开通微信会员卡
//		JSONObject json = wposHttpClient.getMerchantCardByOpenId(openId, mid);
//		// 解析返回值
//		String cardId = null;
//		if (json.containsKey("code")) {
//			int code = json.getIntValue("code");
//			if (code == NOCARD) {
//				// 如果code=5,则说明没有对应的微信会员卡
//				// 如果没有微信会员卡，则通过open_id自动注册为微信会员卡
//				json = wposHttpClient.registerVipCard(openId, mid, "","");
//				code = json.getIntValue("code");
//				if (code == SUCCESS) {
//					JSONObject cardVip = json.getJSONObject("result");
//					// 获取对应的会员卡卡号
//					cardId = cardVip.getString("id");
//				} else {
//					// TODO 错误处理
//				}
//			} else if (code == SUCCESS) {
//				// 如果code=0,则说明对应的微信会员卡已经存在
//				// 如果已经存在，则把对应的银行卡绑定到此微信会员卡上
//				JSONObject cardVip = json.getJSONObject("result");
//				// 获取对应的会员卡卡号
//				cardId = cardVip.getString("id");
//			}
//		}
//		
//		MrtTicketDef ticketDef = ticketDefService.get(ticketDefId);
//		if (ticketDef == null) {
//			// TODO 错误处理
//			return new JSONObject();
//		}
//		
//		MrtTicketInfo ticketInfo = mrtTicketInfoService.getByTicketDefIdAndCardIdAndMid(ticketDefId, cardId, mid);
//		if (ticketInfo == null) {
//			// 跟新券领用数量
//			int used = ticketDef.getHbUseNum();
//			ticketDef.setHbUseNum(++used);
//			ticketDefService.update(ticketDef);
//			// 为用户创建卡券实例
//			ticketInfo = new MrtTicketInfo();
//			ticketInfo.setTicketId(ticketDef.getId());
//			ticketInfo.setCardId(cardId);
//			ticketInfo.setMid(mid);
//			ticketInfo.setWxAdded('0');
//			ticketInfo.setHbShared("0");
//			ticketInfo.setValidFlag("1");
//			ticketInfo.setRemark("摇一摇");
//			ticketInfo.setStartTime(Function.formatDate("yyyy-MM-dd HH:mm:ss"));
//			if (ticketDef.getValidPeriod() != null
//					&& ticketDef.getValidPeriod() != "-1") {
//				int add = Integer.valueOf(ticketDef.getValidPeriod()).intValue();
//				Date day = Function.addDay(new Date(), add);
//				ticketInfo.setExpriyTime(Function.formatDate(day,
//						"yyyy-MM-dd HH:mm:ss"));
//			}
//			String ticketNo = wposHttpClient.getTicketInfoNO(mid);
//			ticketInfo.setTicketNo(ticketNo);
//			ticketInfo = mrtTicketInfoService.save(ticketInfo);
//		}
//		
//		String valid = ticketInfo.getValidFlag();
//		String ticketNo = ticketInfo.getTicketNo();
//		
//		JSONObject res= new JSONObject();
//		res.put("valid", valid);
//		res.put("ticketNo", ticketNo);
//		
//		return res;
//	}
	
	/**
	 * 生成二维码
	 * 
	 * @param openId
	 * @param mid
	 * @param response
	 * @throws IOException 
	 * @throws WriterException 
	 */
	@RequestMapping(value = "/get_qrcode")
	public void getQRcode(
			@RequestParam(value = "ticketNo", required = true) String ticketNo,
			String random, HttpServletResponse response) throws IOException, WriterException {
		String content = ticketNo;
		OutputStream stream = response.getOutputStream();
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.MARGIN, 1);
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = multiFormatWriter.encode(content,
				BarcodeFormat.QR_CODE, 400, 400, hints);
		MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
	}

	@RequestMapping(value = "/choujiang")
	public ModelAndView choujiang() {
		return new ModelAndView("zhanhui/choujiang528");
	}
	
	/**
	 * 摇一摇单张券，会员券，微信券，红包分享
	 * 
	 * @param openId
	 * @param mid
	 * @return
	 */
	@RequestMapping(value = "/index612", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView index612(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "ticketDefId", required = true) String ticketDefId,
			Model model, HttpServletRequest httpRequest) {

		MrtTicketDef ticketDef = ticketDefService.get(ticketDefId);
		if ("0".equals(ticketDef.getUsedFlag())) {// 卡券已经停用
			return new ModelAndView("error").addObject("err_message", "暂无优惠券");
		}
		
		if (ticketDef.getWxFlag() == '1' && ticketDef.getWxCodeId() != null) {// 微信券
			model.addAttribute("wxCodeId", ticketDef.getWxCodeId());

			// 请求微信 js api的完整页面地址
			String dns = messageSource.getMessage(SysConstants.SERVICE_DNS,
					null, Locale.ENGLISH);
			model.addAttribute("dns", dns);

			String baseUrl = "http://" + dns
					+ httpRequest.getSession().getServletContext()
							.getContextPath();
			StringBuffer tmpUrl = new StringBuffer();
			tmpUrl.append(baseUrl);
			tmpUrl.append("/zhanhui/index528");
			tmpUrl.append("?wechat_card_js=1");
			tmpUrl.append("&mid=").append(mid);
			tmpUrl.append("&openId=").append(openId);
			tmpUrl.append("&ticketDefId=").append(ticketDefId);
			String url = tmpUrl.toString();
			// 请求微信api的ticket
			String jsTicket = null;
			try {
				jsTicket = wxAuthentication.getJsTicket(mid);
			} catch (Exception e) {
				log.error(e.getMessage());
				return new ModelAndView("error").addObject("err_message",
						e.getMessage());
			}
			// 微信 js config 签名
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			model.addAllAttributes(ret);

			try {
				String signature = WxSignUtil.extSign(
						wxAuthentication.getCardTicket(mid),
						ticketDef.getWxCodeId(), ret.get("timestamp"), "", "");
				model.addAttribute("ext_signature", signature);
			} catch (Exception e) {
				log.error(e.getMessage());
				return new ModelAndView("error").addObject("err_message",
						e.getMessage());
			}
			
			model.addAttribute("appId", sysWxChildMerchantTokenService.getByWxAppIdAndMidAndPrimaryId(mid).getWxAppId());
		}
		
		model.addAttribute("mid", mid);
		model.addAttribute("openId", openId);
		model.addAttribute("ticketDefId", ticketDefId);
		
		return new ModelAndView("zhanhui/index612");
	}
	
}
